'use client';

import { useState, useEffect, useMemo, useCallback } from 'react';
import { PlayInfo } from '@/lib/utils/types';
import { videoEvents } from '@/lib/video/video-events';

interface UsePlaylistProps {
  playList: PlayInfo[];
  currentIndex?: number;
  onEpisodeChange?: (index: number) => void;
}

export function usePlaylist({ playList, currentIndex, onEpisodeChange }: UsePlaylistProps) {
  const [activeIndex, setActiveIndex] = useState<number>(currentIndex ?? 0);
  const [isReversed, setIsReversed] = useState(false);

  // 当currentIndex变化时更新状态
  useEffect(() => {
    if (currentIndex !== undefined) {
      setActiveIndex(currentIndex);
    }
  }, [currentIndex]);

  // 切换排序方向
  const toggleSort = useCallback(() => {
    setIsReversed(!isReversed);
  }, [isReversed]);

  // 获取排序后的播放列表
  const sortedPlayList = useMemo(() => {
    const sorted = [...playList];
    if (isReversed) {
      return sorted.reverse();
    }
    return sorted;
  }, [playList, isReversed]);

  // 获取排序后的活动索引
  const sortedActiveIndex = useMemo(() => {
    if (isReversed) {
      return playList.length - 1 - activeIndex;
    }
    return activeIndex;
  }, [activeIndex, isReversed, playList.length]);

  // 处理集数切换
  const handleEpisodeClick = useCallback((item: PlayInfo) => {
    if (!item || !item.url) {
      console.error('无效的选集信息或URL为空', item);
      return;
    }

    // 查找原始索引（在原始列表中的位置）
    const originalIndex = playList.findIndex(ep => ep.url === item.url);
    if (originalIndex === -1) {
      console.error('找不到选集对应的索引:', item);
      return;
    }

    console.log('处理选集点击:', originalIndex, item.url);
    
    // 发送切换选集事件
    const success = videoEvents.switchEpisode(item.url, item.name, originalIndex);
    if (success) {
      // 更新当前活动索引（使用原始索引）
      setActiveIndex(originalIndex);
      // 执行回调（使用原始索引）
      onEpisodeChange?.(originalIndex);
    } else {
      console.error('选集切换事件派发失败');
    }
  }, [onEpisodeChange, playList]);

  return {
    activeIndex,
    sortedActiveIndex,
    handleEpisodeClick,
    isReversed,
    toggleSort,
    sortedPlayList,
  };
}